const express = require('express');
const { body, validationResult } = require('express-validator');
const { authenticateToken } = require('./auth');
const { trafficConfigQueries, trafficDetailQueries, monitorLinkQueries } = require('../database/queries');
const { generateMonitorToken } = require('../utils/security');
const { maskPhoneInObject, maskPhoneInArray } = require('../utils/phoneUtils');
const axios = require('axios');

const router = express.Router();

// 提交流量配置
router.post('/submit', authenticateToken, [
  body('token').notEmpty().withMessage('Token不能为空'),
  body('phone').isMobilePhone('zh-CN').withMessage('手机号格式不正确'),
  body('operator').notEmpty().withMessage('运营商不能为空')
], async (req, res) => {
  try {
    // 检查验证错误
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '输入验证失败',
        errors: errors.array()
      });
    }

    const { token, phone, operator, appId } = req.body;
    const userId = req.user.userId;

    // 保存配置到数据库
    const result = await trafficConfigQueries.create(userId, token, phone, operator, appId);

    res.json({
      success: true,
      message: '配置保存成功',
      configId: result.lastID
    });
  } catch (error) {
    console.error('保存配置错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 删除流量配置
router.delete('/delete/:id', authenticateToken, async (req, res) => {
  try {
    const configId = req.params.id;
    const userId = req.user.userId;

    // 验证配置是否属于当前用户
    const config = await trafficConfigQueries.findById(configId);
    if (!config || config.user_id !== userId) {
      return res.status(404).json({
        success: false,
        message: '配置不存在或无权限删除'
      });
    }

    // 软删除配置
    await trafficConfigQueries.delete(configId, userId);

    res.json({
      success: true,
      message: '配置删除成功'
    });
  } catch (error) {
    console.error('删除配置错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 生成监控页面URL
router.post('/generate', authenticateToken, async (req, res) => {
  // console.log(req)
  try {
    const { configId } = req.body;
    const userId = req.user.userId;

    // 验证配置是否属于当前用户
    const config = await trafficConfigQueries.findById(configId);
    if (!config || config.user_id !== userId) {
      return res.status(404).json({
        success: false,
        message: '配置不存在或无权限'
      });
    }

    // 生成安全的监控令牌
    const monitorToken = generateMonitorToken();
    
    // 生成前端监控页面URL（使用令牌而不是配置ID）
    // const host = req.get('host');
    // const frontendHost = process.env.NODE_ENV === 'production' 
    //   ? host 
    //   : host.replace(':3000', ':5173');
    // const monitorUrl = `${req.protocol}://${host}/monitor/${monitorToken}`;
    // console.log(req.get('host'));
      // console.log(req.get('Origin'));
    const monitorUrl = `${req.get('Origin')}/flow-app/#/monitor/${monitorToken}`;
    
    // 创建监控链接记录（自动维护最多5条）
    await monitorLinkQueries.create(configId, monitorUrl, monitorToken);

    res.json({
      success: true,
      message: '监控链接生成成功',
      monitorUrl
    });
  } catch (error) {
    console.error('生成监控链接错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取流量详情（通过配置ID，需要认证）
router.get('/detail/:configId', authenticateToken, async (req, res) => {
  try {
    const configId = req.params.configId;
    const userId = req.user.userId;

    // 获取配置信息并验证所有权
    const config = await trafficConfigQueries.findById(configId);
    if (!config || !config.is_active || config.user_id !== userId) {
      return res.status(404).json({
        success: false,
        message: '配置不存在或无权限访问'
      });
    }

    // 获取历史流量数据
    const trafficHistory = await trafficDetailQueries.findByConfigId(configId, 10);
    
    // 获取最新流量数据
    const latestTraffic = await trafficDetailQueries.findLatestByConfigId(configId);

    // 解析详细数据
    const processedHistory = trafficHistory.map(item => ({
      ...item,
      detailed_data: item.detailed_data ? JSON.parse(item.detailed_data) : null
    }));

    const processedLatest = latestTraffic ? {
      ...latestTraffic,
      detailed_data: latestTraffic.detailed_data ? JSON.parse(latestTraffic.detailed_data) : null
    } : null;

    res.json({
      success: true,
      data: {
        config: maskPhoneInObject({
          phone: config.phone,
          operator: config.operator,
          appId: config.app_id
        }),
        latest: processedLatest,
        history: processedHistory
      }
    });
  } catch (error) {
    console.error('获取流量详情错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 通过监控令牌获取流量详情（公开访问）
router.get('/monitor/:token', async (req, res) => {
  try {
    const monitorToken = req.params.token;

    // 根据监控令牌查找配置
    const config = await monitorLinkQueries.findConfigByToken(monitorToken);
    if (!config) {
      return res.status(404).json({
        success: false,
        message: '监控链接无效或已失效'
      });
    }

    // 获取历史流量数据
    const trafficHistory = await trafficDetailQueries.findByConfigId(config.id, 10);
    
    // 获取最新流量数据
    const latestTraffic = await trafficDetailQueries.findLatestByConfigId(config.id);

    // 解析详细数据
    const processedHistory = trafficHistory.map(item => ({
      ...item,
      detailed_data: item.detailed_data ? JSON.parse(item.detailed_data) : null
    }));

    const processedLatest = latestTraffic ? {
      ...latestTraffic,
      detailed_data: latestTraffic.detailed_data ? JSON.parse(latestTraffic.detailed_data) : null
    } : null;

    res.json({
      success: true,
      data: {
        config: maskPhoneInObject({
          phone: config.phone,
          operator: config.operator,
          appId: config.app_id
        }),
        latest: processedLatest,
        history: processedHistory,
        configId: config.id // 添加configId供前端使用
      }
    });
  } catch (error) {
    console.error('获取监控数据错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取用户的所有配置
router.get('/configs', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.userId;
    const configs = await trafficConfigQueries.findByUserId(userId);

    res.json({
      success: true,
      data: maskPhoneInArray(configs)
    });
  } catch (error) {
    console.error('获取配置列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取配置的监控链接列表
router.get('/monitor-links/:configId', authenticateToken, async (req, res) => {
  try {
    const configId = req.params.configId;
    const userId = req.user.userId;

    // 验证配置是否属于当前用户
    const config = await trafficConfigQueries.findById(configId);
    if (!config || config.user_id !== userId) {
      return res.status(404).json({
        success: false,
        message: '配置不存在或无权限访问'
      });
    }

    // 获取监控链接列表
    const monitorLinks = await monitorLinkQueries.findByConfigId(configId);

    res.json({
      success: true,
      data: monitorLinks
    });
  } catch (error) {
    console.error('获取监控链接列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 删除监控链接
router.delete('/monitor-link/:linkId', authenticateToken, async (req, res) => {
  try {
    const linkId = req.params.linkId;
    const userId = req.user.userId;

    // 这里需要额外验证，确保链接属于用户的配置
    const result = await monitorLinkQueries.delete(linkId, 0, userId);

    res.json({
      success: true,
      message: '监控链接删除成功'
    });
  } catch (error) {
    console.error('删除监控链接错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 刷新流量数据
router.post('/refresh/:configId', async (req, res) => {
  try {
    const configId = req.params.configId;

    // 获取配置信息
    const config = await trafficConfigQueries.findById(configId);
      // console.log(JSON.stringify(config));
    if (!config || !config.is_active) {
      return res.status(404).json({
        success: false,
        message: '配置不存在或已禁用'
      });
    }

    // 调用第三方接口获取流量数据
    try {
      // 优先使用新的第三方接口
      let response;
      try {
        response = await axios.post('http://localhost:3000/flowapi/third-party/new-traffic-data', {
          token: config.token,
          phone: config.phone,
          operator: config.operator,
          appId: config.app_id,
          configId: configId,
          config: config
        });
      } catch (newApiError) {
        console.log('新接口调用失败，回退到原接口:', newApiError.message);
        // 如果新接口失败，回退到原接口
        response = await axios.post('http://localhost:3000/flowapi/third-party/traffic-data', {
          token: config.token,
          phone: config.phone,
          operator: config.operator,
          appId: config.app_id,
          configId: configId,
          config: config
        });
      }

      const trafficData = response.data.data;

      // 保存到数据库，包含packageName和freeflow信息
      const dataForDb = {
        ...trafficData,
        packageName: trafficData.packageName || '未知套餐',
        freeflow: trafficData.Freeflow || 0
      };
      await trafficDetailQueries.create(configId, dataForDb);

      res.json({
        success: true,
        message: '流量数据刷新成功',
        data: trafficData
      });
    } catch (apiError) {
      console.error('调用第三方接口失败:', apiError);
      res.status(500).json({
        success: false,
        message: '获取流量数据失败'
      });
    }
  } catch (error) {
    console.error('刷新流量数据错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 监控模式下刷新流量数据（通过token获取configId）
router.post('/refresh-monitor/:token', async (req, res) => {
  try {
    const monitorToken = req.params.token;

    // 根据监控令牌查找配置
    const config = await monitorLinkQueries.findConfigByToken(monitorToken);
    if (!config) {
      return res.status(404).json({
        success: false,
        message: '监控链接无效或已失效'
      });
    }

    const configId = config.id;

    // 调用第三方接口获取流量数据
    try {
      // 优先使用新的第三方接口，与认证模式保持一致
      let response;
      try {
        response = await axios.post('http://localhost:3000/flowapi/third-party/new-traffic-data', {
          token: config.token,
          phone: config.phone,
          operator: config.operator,
          appId: config.app_id,
          configId: configId,
          config: config
        });
      } catch (newApiError) {
        console.log('新接口调用失败，回退到原接口:', newApiError.message);
        // 如果新接口失败，回退到原接口
        response = await axios.post('http://localhost:3000/flowapi/third-party/traffic-data', {
          token: config.token,
          phone: config.phone,
          operator: config.operator,
          appId: config.app_id,
          configId: configId,
          config: config
        });
      }

      const trafficData = response.data.data;

      // 保存到数据库，包含packageName和freeflow信息
      const dataForDb = {
        ...trafficData,
        packageName: trafficData.packageName || '未知套餐',
        freeflow: trafficData.Freeflow || 0
      };
      await trafficDetailQueries.create(configId, dataForDb);

      res.json({
        success: true,
        message: '流量数据刷新成功',
        data: trafficData
      });
    } catch (apiError) {
      console.error('调用第三方接口失败:', apiError);
      res.status(500).json({
        success: false,
        message: '获取流量数据失败'
      });
    }
  } catch (error) {
    console.error('监控模式刷新流量数据错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 手动清理历史记录接口（管理员功能）
router.post('/cleanup-history', authenticateToken, async (req, res) => {
  try {
    console.log('手动清理历史记录...');
    const result = await trafficDetailQueries.cleanupHistoryRecords();
    
    res.json({
      success: true,
      message: '历史记录清理完成',
      data: {
        cleanedConfigs: result.cleaned,
        description: '每个配置保留最新10条记录'
      }
    });
  } catch (error) {
    console.error('手动清理历史记录失败:', error);
    res.status(500).json({
      success: false,
      message: '清理历史记录失败'
    });
  }
});

module.exports = router;
